
var Inform = require('../models/inform/inform')
var Chat = require('../models/chat/chat')


var illegalArr = []

module.exports = function(io) {

  io.of('/inform').on('connection', function(socket) {

    // Inform.find({}, function(err, informs) {
    //   if (!err) {
    //     socket.emit('inform list', {
    //       list: informs.reverse()
    //     })
    //   }
    // })

    // socket.on('new inform', function(data) {
    //   Inform.insert(data, function(err) {
    //     if (!err) {
    //       socket.broadcast.emit('new inform', data)
    //     }
    //   })
    // })

  })

  io.of('/spit').on('connection', function(socket) {

    Chat.find({}).sort({createdAt: -1}).limit(15).exec(function(err, spits) {
      if (err) {
        console.log('socket err = ' + err)
      } else {
        socket.emit('spit list', {
          list: spits
        })
      }

    })

    socket.on('new spit', function(data) {
      if (illegalArr.indexOf(data.handler.name) > -1) {
        socket.emit('stop spit', {
          msg: '禁言期间不能发言'
        })
      } else {
        if (data.handler.id == -1) {
          data.createdAt = new Date()
          socket.emit('new spit', data)
          socket.broadcast.emit('new spit', data)
        } else {
          new Chat(data).save(function (err, chat) {
            if (err) {
              console.log('socket err = ' + err)
            }
            socket.emit('new spit', chat)
            socket.broadcast.emit('new spit', chat)
          })

        }

      }
    })

    socket.on('illegal', function(data) {
      var handler = data.handler
      if (illegalArr.indexOf(handler.name) == -1) {
        illegalArr.push(handler.name)
        data = {
          inform: handler.name + '试图发送违规内容，被系统禁言1分钟',
          createdAt: new Date()
        }

        socket.emit('new spit', data)
        socket.broadcast.emit('new spit', data)
        setTimeout(function() {
          illegalArr = illegalArr.filter(function(item) {
            return item != handler.name
          })
        }, 60000)
      }


    })

  })
}